/*
 * Created by JFormDesigner on Sun Mar 23 17:06:46 CST 2025
 */

package com.xzp.bams.server;

import com.xzp.bams.service.Bank;
import com.xzp.bams.utils.ThreadPool;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CyclicBarrier;
import javax.swing.*;

/**
 * @author 许志鹏
 */
public class ServerPanel extends JPanel {
//
    ServerSocket ss;
    Socket s;
    //集合容器，存储所有连接进来的socket
    CopyOnWriteArrayList<Socket> clients;
    Bank bank;
    //线程池
    ThreadPool pool;
    //标志位
    boolean accept = false;
    public ServerPanel() {
        clients = new CopyOnWriteArrayList<>();
        bank = Bank.getInstance();
        pool=new ThreadPool(15,25);
        initComponents();
    }

    //核心工作 一旦计数器+1后，达到循环屏障的条件， 则执行客户端接入，分配ServerTasker业务员
    private void startWork() {
        while (accept){
            try {
                //等待接入客户端
                s = ss.accept();
                System.out.println("客户端成功接入~");

                if(s!=null && clients!=null){
                    clients.add(s);
                    //派出线程池中的线程，执行“业务员”的任务
                    pool.execute(new ServerTasker(bank , s));
                }

            } catch (SocketException e) {
                JOptionPane.showMessageDialog(this , "服务器已关闭！");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    private void startButton1(ActionEvent e) {
        // TODO add your code here

        CyclicBarrier barrier = new CyclicBarrier(1 , ()->startWork());

        if(ss==null){
            //线程池中，派出线程执行任务
            pool.execute(()->{
                try {
                    //启动服务器
                    ss = new ServerSocket(8080);

                    //设置按钮状态
                    startButton1.setEnabled(false);
                    closeButton1.setEnabled(true);

                    //设置允许接入客户端
                    accept = true;

                    //计数器 +1
                    barrier.await();
                } catch (IOException | InterruptedException | BrokenBarrierException ex) {
                    throw new RuntimeException(ex);
                }
            });
        }else{
            JOptionPane.showMessageDialog(this,"服务器已启动！");
        }
    }

    private void closeButton1(ActionEvent e) {
        // TODO add your code here
        if(ss==null){
            JOptionPane.showMessageDialog(this , "服务器未开启！");
            return;
        }

        //服务器是处于开启状态，且未被关闭
        if(ss!=null && !ss.isClosed()){
            // 释放客户端资源
            if(clients!=null && clients.size()>0){
                //迭代clients客户端，进行socket一一关闭
                clients.forEach(socket -> {
                    if(socket!=null){
                        try {
                            socket.close();
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                });
            }
            //清空集合
            clients.clear();

            // 设置按钮状态
            startButton1.setEnabled(true);
            closeButton1.setEnabled(false);

            // 改变无限接入客户端的标志 false不再接入客户端
            accept = false;

            // 释放服务端资源
            try {
                ss.close();
                ss = null;
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this , "服务器未正常关闭！");
            }
        }else{
            JOptionPane.showMessageDialog(this , "服务器已关闭！");
        }
    }


    private void startButton2(ActionEvent e) {
        //2.跳转至RankPanel界面
        CardLayout cardLayout = (CardLayout)this.getParent().getLayout();
        cardLayout.show(this.getParent() , "rankPanel");

    }




    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        label1 = new JLabel();
        startButton1 = new JButton();
        closeButton1 = new JButton();
        startButton2 = new JButton();

        //======== this ========
        setLayout(null);

        //---- label1 ----
        label1.setText("ATM  \u670d\u52a1\u5668");
        add(label1);
        label1.setBounds(110, 25, 145, 45);

        //---- startButton1 ----
        startButton1.setText("\u5f00\u542f\u670d\u52a1");
        startButton1.addActionListener(e -> {
			startButton1(e);
		});
        add(startButton1);
        startButton1.setBounds(new Rectangle(new Point(20, 145), startButton1.getPreferredSize()));

        //---- closeButton1 ----
        closeButton1.setText("\u5173\u95ed\u670d\u52a1");
        closeButton1.addActionListener(e -> {
			closeButton1(e);
		});
        add(closeButton1);
        closeButton1.setBounds(new Rectangle(new Point(200, 145), closeButton1.getPreferredSize()));

        //---- startButton2 ----
        startButton2.setText("\u5f00\u542f\u4e0a\u5e1d\u89c6\u89d2");
        startButton2.addActionListener(e -> {
			rank(e);
			startButton2(e);
		});
        add(startButton2);
        startButton2.setBounds(180, 220, 120, 30);

        setPreferredSize(new Dimension(380, 300));
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    private void rank(ActionEvent e) {
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel label1;
    private JButton startButton1;
    private JButton closeButton1;
    private JButton startButton2;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
